const mongoose = require('mongoose')

/**
 * 当前项目模型
 * - currentProjectId: 当前项目记录ID
 * - status: 项目状态（1:进行中, 2:已完成, 3:已暂停, 4:已取消）
 * - startDate: 项目开始时间
 * - expectedEndDate: 预期结束时间
 * - actualEndDate: 实际结束时间
 * - files: 关联图片文件
 * - projectName: 项目名称
 * - projectType: 项目类型
 * - priority: 优先级（1:低, 2:中, 3:高, 4:紧急）
 * - description: 项目描述
 * - teamMembers: 团队成员列表
 * - budget: 项目预算
 * - progress: 项目进度（0-100）
 * - clientName: 客户名称
 * - projectManager: 项目经理
 */
const CurrentProjectSchema = new mongoose.Schema({
  currentProjectId: {
    type: String,
    required: true,
    default: function () {
      return this._id.toString()
    }
  },
  status: {
    type: Number,
    required: true,
    enum: [1, 2, 3, 4], // 1:进行中, 2:已完成, 3:已暂停, 4:已取消
    default: 1
  },
  startDate: {
    type: Date,
    required: true,
    get: v => v.toISOString().split('T')[0]
  },
  expectedEndDate: {
    type: Date,
    required: true,
    get: v => v.toISOString().split('T')[0]
  },
  actualEndDate: {
    type: Date,
    get: v => v ? v.toISOString().split('T')[0] : null
  },
  year: {
    type: Number,
    required: true,
    default: function () {
      const dateObj = this.startDate instanceof Date ? this.startDate : new Date(this.startDate)
      return dateObj.getUTCFullYear()
    }
  },
  files: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'File',
    required: true
  },
  projectName: {
    type: String,
    required: true,
    maxlength: 100
  },
  projectType: {
    type: String,
    required: true,
    maxlength: 50
  },
  priority: {
    type: Number,
    required: true,
    enum: [1, 2, 3, 4], // 1:低, 2:中, 3:高, 4:紧急
    default: 2
  },
  description: {
    type: String,
    required: true,
    maxlength: 1000
  },
  teamMembers: [
    {
      type: String,
      maxlength: 50
    }
  ],
  budget: {
    type: Number,
    min: 0
  },
  progress: {
    type: Number,
    required: true,
    min: 0,
    max: 100,
    default: 0
  },
  clientName: {
    type: String,
    maxlength: 100
  },
  projectManager: {
    type: String,
    required: true,
    maxlength: 50
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
})

// 更新时自动设置updatedAt
CurrentProjectSchema.pre('save', function(next) {
  this.updatedAt = Date.now()
  next()
})

CurrentProjectSchema.set('toJSON', { getters: true })
CurrentProjectSchema.index({ year: 1, currentProjectId: 1, status: 1, priority: 1 })

module.exports = mongoose.model('CurrentProject', CurrentProjectSchema)